translator.plugin('detectPageLanguage', {

  /**
   * Attempts to determine the langauge of a given 
   * document based on the lang attribute. returns 
   * a language object if worked, null otherwise.
   *
   * @access private
   * @return mixed
   */
  getPageLanguageInformation : function (dom) {
    var lang = null;
    var elementsWithLangAttr = dom.querySelectorAll('[lang]');

    if (0 < elementsWithLangAttr.length) {
      var langAttr = elementsWithLangAttr[0].getAttribute('lang');
      langAttr.split('-').forEach(function (lng) {
          var $lng = translator.getLanguage(lng);
          if (false !== $lng && null === lang) {
            lang = $lng;
          }
      });
    }

    return lang;
  },

  /**
   * Generates a language sample from the given document.
   * 
   * @access private
   * @return string 
   */
   generateSampleFromPage : function (dom) {
      var sample = dom.title + ' ';
      var selectors = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'a', 'cite','div', '*'];

      while (sample.length < 128 && 0 < selectors.length) {
        var nodes = dom.body.querySelectorAll(selectors.shift());
        if (0 < nodes.length) {
          for (var n = 0, l = nodes.length; n < l; n++) {
            sample += nodes[n].textContent;
          }
        }
      }
      return sample.substring(0, 128);
   },
  
  /**
   *
   * @access public
   */
  method : function (options) {
    var lang = this.getPageLanguageInformation(options.dom);
    if (null !== lang) {
      options.success(lang);
    } else {
      var sample = this.generateSampleFromPage(options.dom);
      translator.detect({
        text : sample,
        success : function (lang) {
          options.success(lang);
        },
        fail : function (e) {
          if ("error" in options) {
            options.error(e);
          }
        }
      });
    }
  }
});
